/* NOTICE
 
    Jim - the Java Image Manager, copyright (c) 2005 - 2007 Grant Gardner 
 
    Jim is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Jim is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  
    In addition, as a special exception, you are permitted to link this code
    with the 3rd party libraries required to compile this file and to
    distribute a linked combination including them. You must obey the
    GNU General Public License in all respects for all of the code except for
    those 3rd party libraries that are licenced under terms incompatible with the
    GNU General Public License.  
 
 
 NOTICE */

package au.com.lastweekend.jim.io.exif;

import org.apache.log4j.Logger;

import au.com.lastweekend.jim.io.metadata.Directory;
import au.com.lastweekend.jim.io.metadata.MetadataException;

/**
 * 
 * 
 * @version $Id: ThumbnailTiffDirectoryReader.java,v 1.2 2005/06/09 11:15:37 ggardner Exp $
 * @author <a href="mailto:grant@lastweekend.com.au"> <Grant Gardner> </a>
 */
public class ThumbnailTiffDirectoryReader extends AbstractTiffTagReader {

    private static final Logger LOG = Logger.getLogger(ThumbnailTiffDirectoryReader.class);

    /**
     * @param data
     */
    public ThumbnailTiffDirectoryReader(byte[] data) {

        super(data);
    }

    @Override
    public Directory extract(Directory parentDirectory) throws TiffTagProcessingException {

        setDirectory(new ThumbnailTiffDirectory());
        processTiffTags();
        extractThumbnail();
        return getDirectory();
    }

    /**
     * 
     * @see au.com.lastweekend.jim.io.exif.AbstractTiffTagReader#getLinkedDirectoryReader()
     */
    @Override
    protected AbstractTiffTagReader getLinkedDirectoryReader() {

        return null;
    }

    private void extractThumbnail() throws TiffTagProcessingException {

        Directory directory = getDirectory();

        int compression = 0;
        int offsetTag;
        int lengthTag;

        int offset;
        int length;
        try {

            if (directory.containsTag(ExifDirectory.TAG_COMPRESSION)) {
                compression = directory.getInt(ExifDirectory.TAG_COMPRESSION);
            } else if (directory.containsTag(ExifDirectory.TAG_THUMBNAIL_OFFSET)) {
                compression = 6;
            } else if (directory.containsTag(ExifDirectory.TAG_STRIP_OFFSETS)) {
                compression = 1;
            }

            switch (compression) {
                case 1 : // TIFF
                    offsetTag = ExifDirectory.TAG_STRIP_OFFSETS;
                    lengthTag = ExifDirectory.TAG_STRIP_BYTE_COUNTS;
                    break;

                case 6 : // JPEG
                    offsetTag = ExifDirectory.TAG_THUMBNAIL_OFFSET;
                    lengthTag = ExifDirectory.TAG_THUMBNAIL_LENGTH;
                    break;

                default :
                    return;
            }

            if (!directory.containsTag(lengthTag) || !directory.containsTag(offsetTag)) {
                return;
            }

            offset = directory.getInt(offsetTag);
            length = directory.getInt(lengthTag);

        } catch (MetadataException e) {
            LOG.warn("Unable to extract thumbnail from thumbnail tags", e);
            return;
        }

        byte[] data = getData();

        if (offset + length > data.length) {
            // The Sony DCR* series seems to have length extending 1 byte past
            // the end of the data.
            LOG.warn("Thumbnail length exceeds available data, truncating");

            length = data.length - offset;
        }
        // The CANON EOS sample from drew noakes, contained a ZERO length
        // thumbnail entry.
        if (length > 0 && offset + length <= data.length) {

            byte[] result = new byte[length];
            for (int i = 0; i < result.length; i++) {
                result[i] = data[offset + i];
            }

            // This is a FAKE Tag. Writer will not write this as a tag
            directory.setTag(ThumbnailTiffDirectory.TAG_THUMBNAIL_DATA, TiffTagFormat.FMT_BYTE, result);
        }

    }

}